package com.bytz.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bytz.common.api.vo.Result;
import com.bytz.common.constant.CacheConstant;
import com.bytz.common.system.query.QueryGenerator;
import com.bytz.common.system.vo.LoginUser;
import com.bytz.common.util.SecurityUtils;
import com.bytz.modules.system.constant.SysAuthConstants;
import com.bytz.modules.system.dto.FetchAuditUserInfo;
import com.bytz.modules.system.entity.SysDepart;
import com.bytz.modules.system.model.DepartIdModel;
import com.bytz.modules.system.model.SysDepartTreeModel;
import com.bytz.modules.system.service.ISysDepartService;
import com.bytz.modules.system.util.AuditUtil;
import com.bytz.modules.system.vo.DepartInputParams;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 部门表 前端控制器
 * <p>
 *
 * @Author: Steve @Since： 2019-01-22
 */
@RestController
@RequestMapping("/sys/sysDepart")
@Slf4j
@Api(tags = "部门controller")
public class SysDepartController {

    @Autowired
    private ISysDepartService sysDepartService;

    /**
     * 通过Id获取机构数据
     */
    @ApiOperation("通过Id获取机构数据")
    @RequestMapping(value = "/getById", method = RequestMethod.GET)
    public Result<SysDepart> getById(@RequestParam("id") String id) {
        return Result.ok(sysDepartService.getById(id));
    }

    /**
     * 查询数据 查出所有部门,并以树结构数据格式响应给前端
     */
    @RequestMapping(value = "/queryTreeList", method = RequestMethod.GET)
    public Result<List<SysDepartTreeModel>> queryTreeList() {
        Result<List<SysDepartTreeModel>> result = new Result<>();
        List<SysDepartTreeModel> list = sysDepartService.queryTreeList();
        result.setResult(list);
        result.setSuccess(true);

        return result;
    }

    /**
     * 查询数据 查出本部门及以下或本中心及以下或本公司及以下数据
     *
     * @return
     */
    @RequestMapping(value = "/queryTreeListByViewScope", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('" + SysAuthConstants.DepartPermission.DEPART_VIEW + "')")
    public Result<List<SysDepartTreeModel>> queryTreeListByScope(@RequestParam(name = "menu", required = false) String menu) {
        Result<List<SysDepartTreeModel>> result = new Result<>();
        List<SysDepartTreeModel> list = sysDepartService.queryTreeListByScope(menu);
        result.setResult(list);
        result.setSuccess(true);

        return result;
    }

    /**
     * 查询数据 查出本部门及以下或本中心及以下或本公司及以下数据
     *
     * @return
     */
    @RequestMapping(value = "/queryTreeListByParams", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('" + SysAuthConstants.DepartPermission.DEPART_VIEW + "')")
    public Result<List<SysDepartTreeModel>> queryTreeListByParams(
            DepartInputParams departInputParams, HttpServletRequest request) {
        Result<List<SysDepartTreeModel>> result = new Result<>();
        List<SysDepartTreeModel> list = sysDepartService.queryTreeListByParams(departInputParams, request.getParameterMap());
        result.setResult(list);
        result.setSuccess(true);

        return result;
    }

    /**
     * 查询数据 查出所有部门,并以树结构数据格式响应给前端
     *
     * @return
     */
    @RequestMapping(value = "/queryParentCompany", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('" + SysAuthConstants.DepartPermission.DEPART_VIEW + "')")
    public Result<List<SysDepart>> queryParentCompany(@RequestParam(name = "parentId", required = true) String parentId) {
        Result<List<SysDepart>> result = new Result<>();
        List<SysDepart> list = sysDepartService.queryParentCompany(parentId);
        result.setResult(list);
        result.setSuccess(true);

        return result;
    }

    /**
     * 添加新数据 添加用户新建的部门对象数据,并保存到数据库
     *
     * @param sysDepart
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_EXT_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries = true)
    @PreAuthorize("hasAuthority('" + SysAuthConstants.DepartPermission.DEPART_EDIT + "')")
    public Result<SysDepart> add(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
        Result<SysDepart> result = new Result<SysDepart>();
        String username = SecurityUtils.getUsername();
        sysDepart.setCreateBy(username);
        sysDepartService.saveDepartData(sysDepart, username);
        //清除部门树内存
        // FindsDepartsChildrenUtil.clearSysDepartTreeList();
        // FindsDepartsChildrenUtil.clearDepartIdModel();
        result.success("添加成功！");

        return result;
    }

    /**
     * 编辑数据 编辑部门的部分数据,并保存到数据库
     *
     * @param sysDepart
     * @return
     */
    @RequestMapping(value = "/edit", method = { RequestMethod.PUT, RequestMethod.POST })
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_EXT_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries = true)
    @PreAuthorize("hasAuthority('" + SysAuthConstants.DepartPermission.DEPART_EDIT + "')")
    public Result<SysDepart> edit(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
        String username = SecurityUtils.getUsername();
        sysDepart.setUpdateBy(username);
        Result<SysDepart> result = new Result<SysDepart>();
        SysDepart sysDepartEntity = sysDepartService.getById(sysDepart.getId());
        if (sysDepartEntity == null) {
            result.error500("未找到对应实体");
        } else {
            // 查找该数据是否为公司变部门以及是否做了所属公司关联
            boolean canUpdate = sysDepartService.dataValidation(sysDepartEntity, sysDepart);
            if (!canUpdate) {
                result.error500("无法修改机构类型还有部门引用此公司");
                return result;
            }
            boolean ok = sysDepartService.updateDepartDataById(sysDepart, username);
            // TODO 返回false说明什么？
            if (ok) {
                //清除部门树内存
                //FindsDepartsChildrenUtil.clearSysDepartTreeList();
                //FindsDepartsChildrenUtil.clearDepartIdModel();
                result.success("修改成功!");
            }
        }
        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete", method = { RequestMethod.DELETE, RequestMethod.POST })
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_EXT_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries = true)
    @PreAuthorize("hasAuthority('" + SysAuthConstants.DepartPermission.DEPART_EDIT + "')")
    public Result<SysDepart> delete(@RequestParam(name = "id", required = true) String id) {

        Result<SysDepart> result = new Result<SysDepart>();
        SysDepart sysDepart = sysDepartService.getById(id);
        if (sysDepart == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = sysDepartService.delete(id);
            if (ok) {
                //清除部门树内存
                //FindsDepartsChildrenUtil.clearSysDepartTreeList();
                // FindsDepartsChildrenUtil.clearDepartIdModel();
                result.success("删除成功!");
            }
        }
        return result;
    }


    /**
     * 批量删除 根据前端请求的多个ID,对数据库执行删除相关部门数据的操作
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/deleteBatch", method = { RequestMethod.DELETE, RequestMethod.POST })
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_EXT_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries = true)
    @PreAuthorize("hasAuthority('" + SysAuthConstants.DepartPermission.DEPART_EDIT + "')")
    public Result<SysDepart> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {

        Result<SysDepart> result = new Result<SysDepart>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.sysDepartService.deleteBatchWithChildren(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 查询数据 添加或编辑页面对该方法发起请求,以树结构形式加载所有部门的名称,方便用户的操作
     *
     * @return
     */
    @RequestMapping(value = "/queryIdTree", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('" + SysAuthConstants.DepartPermission.DEPART_VIEW + "')")
    public Result<List<DepartIdModel>> queryIdTree() {
//		Result<List<DepartIdModel>> result = new Result<List<DepartIdModel>>();
//		List<DepartIdModel> idList;
//		try {
//			idList = FindsDepartsChildrenUtil.wrapDepartIdModel();
//			if (idList != null && idList.size() > 0) {
//				result.setResult(idList);
//				result.setSuccess(true);
//			} else {
//				sysDepartService.queryTreeList();
//				idList = FindsDepartsChildrenUtil.wrapDepartIdModel();
//				result.setResult(idList);
//				result.setSuccess(true);
//			}
//			return result;
//		} catch (Exception e) {
//			log.error(e.getMessage(),e);
//			result.setSuccess(false);
//			return result;
//		}
        Result<List<DepartIdModel>> result = new Result<>();
        List<DepartIdModel> list = sysDepartService.queryDepartIdTreeList();
        result.setResult(list);
        result.setSuccess(true);

        return result;
    }

    /**
     * <p>
     * 部门搜索功能方法,根据关键字模糊搜索相关部门
     * </p>
     *
     * @param keyWord
     * @return
     */
    @RequestMapping(value = "/searchBy", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('" + SysAuthConstants.DepartPermission.DEPART_VIEW + "')")
    public Result<List<SysDepartTreeModel>> searchBy(@RequestParam(name = "keyWord", required = true) String keyWord) {
        Result<List<SysDepartTreeModel>> result = new Result<List<SysDepartTreeModel>>();
        List<SysDepartTreeModel> treeList = this.sysDepartService.searhBy(keyWord);
        if (treeList == null || treeList.size() == 0) {
            result.setSuccess(false);
            result.setMessage("未查询匹配数据！");
            return result;
        }
        result.setResult(treeList);
        return result;
    }


    /**
     * 导出excel
     *
     * @param request
     */
    @RequestMapping(value = "/exportXls")
    @PreAuthorize("hasAuthority('" + SysAuthConstants.DepartPermission.DEPART_VIEW + "')")
    public ModelAndView exportXls(SysDepart sysDepart, HttpServletRequest request) {
        // Step.1 组装查询条件
        QueryWrapper<SysDepart> queryWrapper = QueryGenerator.initQueryWrapper(sysDepart, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<SysDepart> pageList = sysDepartService.list(queryWrapper);
        //按字典排序
        Collections.sort(pageList, new Comparator<SysDepart>() {
            @Override
            public int compare(SysDepart arg0, SysDepart arg1) {
                return arg0.getOrgCode().compareTo(arg1.getOrgCode());
            }
        });
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "部门列表");
        mv.addObject(NormalExcelConstants.CLASS, SysDepart.class);
        LoginUser user = SecurityUtils.getLoginUser();
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("部门列表数据", "导出人:" + user.getRealname(), "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_EXT_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries = true)
    @PreAuthorize("hasAuthority('" + SysAuthConstants.DepartPermission.DEPART_VIEW + "')")
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                // orgCode编码长度
                int codeLength = 3;
                List<SysDepart> listSysDeparts = ExcelImportUtil.importExcel(file.getInputStream(), SysDepart.class, params);
                //按长度排序
                Collections.sort(listSysDeparts, new Comparator<SysDepart>() {
                    @Override
                    public int compare(SysDepart arg0, SysDepart arg1) {
                        return arg0.getOrgCode().length() - arg1.getOrgCode().length();
                    }
                });
                for (SysDepart sysDepart : listSysDeparts) {
                    String orgCode = sysDepart.getOrgCode();
                    if (orgCode.length() > codeLength) {
                        String parentCode = orgCode.substring(0, orgCode.length() - codeLength);
                        QueryWrapper<SysDepart> queryWrapper = new QueryWrapper<SysDepart>();
                        queryWrapper.eq("org_code", parentCode);
                        try {
                            SysDepart parentDept = sysDepartService.getOne(queryWrapper);
                            if (!parentDept.equals(null)) {
                                sysDepart.setParentId(parentDept.getId());
                            } else {
                                sysDepart.setParentId("");
                            }
                        } catch (Exception e) {
                            //没有查找到parentDept
                        }
                    } else {
                        sysDepart.setParentId("");
                    }
                    sysDepartService.save(sysDepart);
                }
                return Result.ok("文件导入成功！数据行数：" + listSysDeparts.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    @GetMapping("/queryTreeByIdParam")
    @ApiOperation("根据参数查询部门树")
    public Result<List<SysDepartTreeModel>> queryTreeByIdParam(@RequestParam String startDeptId,
                                     @RequestParam String dataScope,
                                     @RequestParam(required = false) String applyScope,
                                     @RequestParam(required = false) String relativePerson,
                                     @RequestParam(required = false, defaultValue = "false") Boolean unlimit) {
        if (unlimit || StringUtils.isBlank(dataScope)) {
            //获取深圳市水务局所有部门
            List<SysDepartTreeModel> sysDepartTreeModels = sysDepartService.queryTreeList();
            SysDepartTreeModel parentTree;
            if (sysDepartTreeModels.size() == 1) {
                parentTree = sysDepartTreeModels.get(0);
            } else if (sysDepartTreeModels.size() > 0) {
                parentTree = new SysDepartTreeModel();
                parentTree.setId("-1");
                parentTree.setKey("-1");
                parentTree.setOrgCode("");
                parentTree.setDepartName("全部机构");
                parentTree.setTitle("全部机构");

                parentTree.setChildren(sysDepartTreeModels);
            } else {
                parentTree = new SysDepartTreeModel();
                parentTree.setOrgCode("");
                parentTree.setDepartName("未找到机构");
                parentTree.setTitle("未找到机构");
            }

            return Result.ok(Collections.singletonList(parentTree));
        } else {
            FetchAuditUserInfo fetchAuditUserInfo = AuditUtil.calculateFetchAuditUserInfo(startDeptId,
                    dataScope, applyScope,
                    SecurityUtils.getDeptId(),
                    relativePerson);
            List<SysDepartTreeModel> sysDepartTreeModels = sysDepartService.queryTreeList();
            Map<String, SysDepartTreeModel> stringSysDepartTreeModelMap = sysDepartService.convertTreeToMap(sysDepartTreeModels);
            SysDepartTreeModel parentTree = sysDepartService.getParentTree(stringSysDepartTreeModelMap, fetchAuditUserInfo);

            return Result.ok(Collections.singletonList(parentTree));
        }
    }

    /**
     * 获取外部单位（带模糊查询）
     *
     * @param pageNo
     * @param pageSize
     * @param key      关键字
     * @return IPage<SysDepart>
     */
    @ApiOperation(value = "获取外部单位", notes = "获取外部单位")
    @GetMapping(value = "/listExternalCompany")
    public Result<IPage<SysDepart>> queryPageList(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "key", required = false) String key) {
        Page<SysDepart> page = new Page<SysDepart>(pageNo, pageSize);
        IPage<SysDepart> pageList = sysDepartService.listExternalCompany(page, key);
        return Result.ok(pageList);
    }

    @ApiOperation(value = "部门全量数据")
    @GetMapping(value = "/queryAll")
    public Result<List<SysDepart>> queryAllList() {

        List<SysDepart> res = sysDepartService.list();
        return Result.ok(res);
    }
}
